<?php

namespace app\admin\model\booking;

use think\Model;


class Lodgers extends Model
{


    // 表名
    protected $name = 'booking_lodgers';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'type_text'
    ];

    protected static function init()
    {
        self::beforeInsert(function ($row) {
            $data = self::where('type', $row)->where('idnumber')->find();
            if ($data) {
                throw new \Exception("{$row['name']}已存在，无需重复添加");
            }
        });
    }

    public function getTypeList()
    {
        return ['0' => __('Type0'), '1' => __('Type1'), '2' => __('Type2'), '3' => __('Type3')];
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function User()
    {
        return $this->belongsTo('\app\common\model\User', 'user_id', 'id', [], 'LEFT');
    }


    public static function edit($data, $exclude_ids = [], $user_id)
    {
        $ids = [];//订单字段
        $params = [];//校验数据
        foreach ($data as $item) {
            $row = (new self)->where('type', $item['type'])->where('idnumber', $item['idnumber'])->find();
            if ($row) {
                $row->allowField(true)->save($item);
                $ids[] = $row['id'];
                if (!in_array($row['id'], $exclude_ids)) {
                    $params[] = $row;
                }
            } else {
                $item['user_id'] = $user_id;
                $item['createtime'] = time();
                $item['updatetime'] = time();
                $id = (new self)->insertGetId($item);
                $ids[] = $id;
            }
        }
        return [$ids, $params];
    }
}
